#!/usr/bin/env python 
#-*- Coding: UTF-8 -*-

import socket
import struct
import sys
import time
import SocketServer
from  threading import *
import binascii, re
from array import *
from datetime import datetime
#from event import event

match_pub = re.compile("PUBLISH\s(.+?)\s(.+?)\s(\d+)") # PUBLISH NAME IP PORT
published = {}
#listen_ip = "192.168.0.1"
listen_port = 5543
listen_addr = ("0.0.0.0",listen_port)

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
sock.bind(listen_addr)
sock.listen(5)
s = None

while 1:
    try:
        s,addr = sock.accept()
        print addr
        data = s.recv(1024)
        print data
        m = match_pub.match(data)
        if m :
            print "Name:",m.group(1),"Addr: %s:%s"%(m.group(2),m.group(3))
            published[addr] = m.group(1)
            s.send("OK PUBLISH")
            print published
        print "- - - - - - - - - - - - - - - - - - -"
    except KeyboardInterrupt,e:
        if s:
            s.close()
        break
    
